package com.tenebrous.jestic.controller.framwork.system.meta;

import com.tenebrous.jestic.compents.annotations.Weblog;
import com.tenebrous.jestic.compents.annotations.WeblogEnum;
import com.tenebrous.jestic.controller.SupperController;
import com.tenebrous.jestic.entity.framwork.system.MetaDictionary;
import com.tenebrous.jestic.service.framwork.system.MetaDictionaryService;
import com.rain.ops.sdk.dto.ApiResult;
import com.rain.ops.sdk.utils.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

/**
 * 数据字典
 */
@Validated
@RestController
@RequestMapping("/meta/diction")
public class DictionController extends SupperController {

    @Autowired
    private MetaDictionaryService dictService;

    @PostMapping("/get")
    public ApiResult get(@NotBlank String id) {
        MetaDictionary item = dictService.selectByPrimaryKey(id);
        if(item != null) {
            return new ApiResult(200, "查询成功。", item);
        }
        return new ApiResult(999, "查询失败，未找到指定对象。");
    }
    /**
     * 查询
     * @return
     */
    @PostMapping("/query-tree")
    public ApiResult queryTree() {
        return new ApiResult(200, "查询成功。", dictService.queryTree());
    }

    /**
     * 更新对象
     * @param item
     * @return
             */
    @PostMapping("/update")
    @Weblog(description = "更新指定数据字典记录", method = WeblogEnum.UPDATE)
    public ApiResult update(@NotNull MetaDictionary item) {
        if(StringUtils.isNotBlank(item.getId())) {
            item.setUpdateDate(new Date());
            dictService.updateSelective(item);
        } else {
            item.setId(UUIDUtils.randomUUID());
            item.setCreateDate(new Date());
            dictService.saveSelective(item);
        }
        return new ApiResult(200, "更新成功。");
    }

    /**
     * 删除对象
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @Weblog(description = "删除指定数据字典记录", method = WeblogEnum.UPDATE)
    public ApiResult delete(@NotBlank String id) {
        return new ApiResult(200, "删除成功。", dictService.deleteByPrimaryKey(id));
    }

    /**
     * 根据code查询子节点
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/query/code")
    public ApiResult  queryByCode(@NotBlank String code){
        List<MetaDictionary> list = dictService.queryChildListByCode(code);
        return new ApiResult(200, "查询成功。", list);
    }

}
